package net.wwang.blog.controller.space;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import net.wwang.blog.config.ImgZipConfig;
import net.wwang.blog.utils.APIResponse;
import net.wwang.blog.utils.ImageUtil;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

/**
 * 图片上传处理类
 * @author zlzhaoe
 */
@Controller
@RequestMapping("/space")
public class ImgZipController {
	@ApiOperation(value = "图片上传",notes = "多项目图片上传工具类",httpMethod = "POST")
	@RequestMapping(value="/img_upload_compress")
	@ResponseBody
	public void img_upload_compress(
			@ApiParam(name = "file",value="文件（图片）",required = true) @RequestParam(value = "file") MultipartFile file,
			@ApiParam(name = "name",value="项目名称")@RequestParam(value = "name",required = false)String path,
			@ApiParam(name = "scale",value="图片压缩比例:0.0~1.0")@RequestParam(value = "scale",required = false)Double scale,
			HttpServletResponse response) throws IOException {
		String resultImagePath = ImageUtil.imgUploadCompress(file, path,scale);
		Path imgDir = Paths.get(ImgZipConfig.imagePath,resultImagePath);
		FileInputStream is = new FileInputStream(imgDir.toFile());
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/octet-stream; charset=utf-8");
		response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getOriginalFilename() + "\"");
		OutputStream os = response.getOutputStream();
		os.write(IOUtils.toByteArray(is));
		is.close();
		os.close();
		/*if(resultImagePath.equals("0")){
			return  APIResponse.failure("上传失败,处理异常！");
		}else if(resultImagePath.equals("-1")){
			return  APIResponse.failure("非法图片格式！");
		}else{
			return APIResponse.success(resultImagePath);
		}*/
	}
}
